/**
 * Copyright (c) 2010-2011 julewa.com.  
 * All rights reserved. 
 * 
 * @author Huang Benhua
 * @date 2011-6-20
 * 
**/
package com.julewa.freemarker;

import java.util.List;

import com.julewa.Querier;

import freemarker.template.ObjectWrapper;
import freemarker.template.TemplateMethodModelEx;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;
import freemarker.template.utility.DeepUnwrap;

public class FreemarkerMethod implements TemplateMethodModelEx, Querier{
	private Querier method = null;
	private Object NONE;
	public FreemarkerMethod(Querier m){
		method = m;
		try {NONE = ObjectWrapper.SIMPLE_WRAPPER.wrap("");
		} catch (TemplateModelException e) { }
	};
	public FreemarkerMethod(){
		try {
			method = this;
			NONE = ObjectWrapper.SIMPLE_WRAPPER.wrap("");
		} catch (TemplateModelException e) { 
			//
		}
	}
	@Override
	public Object exec(@SuppressWarnings("rawtypes") List args) throws TemplateModelException {
		if(args.isEmpty()){
			Object result = method.execute();
			if(result == null)return NONE;
			return ObjectWrapper.DEFAULT_WRAPPER.wrap(result);
		}
		Object objs[] = args.toArray();
		for(int i = 0; i < objs.length; ++ i){
			if(objs[i] == null)continue;
			objs[i] = DeepUnwrap.unwrap((TemplateModel)objs[i]);
		}
		Object result = method.execute(objs);
		if(result == null)return NONE;
		
		return ObjectWrapper.DEFAULT_WRAPPER.wrap(result);
	}
	
	@Override
	public Object execute(Object... args) {
		return null;
	}
	
};